package com.yuchting.dinneronline.client;

import java.util.Date;
import java.util.Vector;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.yuchting.dinneronline.client.common.CommonDialog;
import com.yuchting.dinneronline.client.common.Config;
import com.yuchting.dinneronline.client.common.Dinner;
import com.yuchting.dinneronline.client.common.Order;
import com.yuchting.dinneronline.client.common.RankPanel;
import com.yuchting.dinneronline.client.common.YesNoHandler;
import com.yuchting.dinneronline.client.common.YuchFlexTable;
import com.yuchting.dinneronline.client.common.YuchJSONObject;
import com.yuchting.dinneronline.client.common.YuchSimplePanel;

public class OrderPanel extends VerticalPanel {
	
	static final DateTimeFormat fsm_orderTimeFormat = DateTimeFormat.getFormat("yyyy MM-dd HH:mm");
	static final Date			fsm_dateTime = new Date();
	
	MainPanel m_mainPanel = null;
	
	VerticalPanel	m_configPanel = new YuchSimplePanel();
	HTML			m_config	= new HTML();
	
	VerticalPanel m_propPanel = new YuchSimplePanel();
	FlexTable	m_propTable = new YuchFlexTable();
	Label		m_username	= new Label();
	Label		m_remain	= new Label();
	Label		m_total		= new Label();
	
	Button		m_quitButton = new Button("退出");
	Button		m_changePassBtn = new Button("更改密码");
		
	VerticalPanel	m_currOrderPanel = new YuchSimplePanel();
	FlexTable		m_currOrderTable = new YuchFlexTable();
	FlexTable		m_formerOrderTable = new YuchFlexTable();
	Vector<Order>	m_currOrderList = new Vector<Order>();
	Vector<Order>	m_formerOrderList = new Vector<Order>();
	
		
	VerticalPanel	m_currDinnerPanel = new YuchSimplePanel();
	FlexTable		m_currDinnerTable = new YuchFlexTable();
		
	public OrderPanel(MainPanel _main){
		m_mainPanel = _main;
		
		m_configPanel.add(m_config);
		
		int t_line = 0;
		CommonDialog.AddLabelWidget(m_propTable, "用户名：", m_username, t_line++);
		CommonDialog.AddLabelWidget(m_propTable, "余额：", m_remain, t_line++);
		CommonDialog.AddLabelWidget(m_propTable, "一共花费：", m_total, t_line++);
		
		m_propPanel.setSpacing(5);
		m_propPanel.add(new HTML("<b style=\"font-size:130%\">我的账户属性：</b>"));
		m_propPanel.add(m_propTable);
		
		HorizontalPanel t_propBtnPanel = new HorizontalPanel();
		t_propBtnPanel.setSpacing(5);
		t_propBtnPanel.add(m_quitButton);
		t_propBtnPanel.add(m_changePassBtn);
		
		m_propPanel.add(t_propBtnPanel);
		
		m_quitButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				m_mainPanel.hide();
				m_mainPanel.m_mainPage.onModuleLoad();
			}
		});
		
		m_changePassBtn.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				new ChangePassDlg(MainPanel.getCurrUser()).show();				
			}
		});

		m_currOrderPanel.add(new HTML("<b style=\"font-size:130%\">我的当前订单：</b>"));
		m_currOrderPanel.add(m_currOrderTable);
		m_currOrderPanel.add(new HTML("<b style=\"font-size:130%\">上次的订单：</b>"));
		m_currOrderPanel.add(m_formerOrderTable);
		
		m_currDinnerPanel.add(new HTML("<b style=\"font-size:130%\">菜单集合：</b>"));
		m_currDinnerPanel.add(m_currDinnerTable);
		
		add(m_configPanel);
		add(m_propPanel);
		add(m_currOrderPanel);
		add(m_currDinnerPanel);		
		
		String t_mainPanelWidth = CommonDialog.getElementWidth(m_mainPanel.getElement());
		
		m_propPanel.setWidth(t_mainPanelWidth);
		m_configPanel.setWidth(t_mainPanelWidth);
		m_currOrderPanel.setWidth(t_mainPanelWidth);
		m_currDinnerPanel.setWidth(t_mainPanelWidth);
		this.setWidth(t_mainPanelWidth);
	}
	
	public void requestData(){
		
		try{
			
			MainPage.fsm_server.getConfig(new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("获取配置信息失败：" + caught.getMessage(), null);
				}

				public void onSuccess(String result) {

					Config t_config = new Config();
					try{
						t_config.fromJSON(new YuchJSONObject(result));
					}catch(Exception e){
						CommonDialog.PopupPrompt("获取配置信息失败：" + e.getMessage(), null);
					}
					
					StringBuffer t_configString = new StringBuffer();

					t_configString.append("<span style=\"font-size:22px\"><strong>出单时间（不能订餐）：")
								.append(t_config.getStartHour()).append(":").append(t_config.getStartMinutes()).append(" - ")
								.append(t_config.getEndHour()).append(":").append(t_config.getEndMinutes()).append("</strong></span><br />")
								.append("<span style=\"font-size:20px\">").append(t_config.getPrompt()).append("</span>");
					
					m_config.setHTML(t_configString.toString());
					
					// refresh the admin config and account panel
					ConfigAccPanel.refreshConfig(t_config);
				}
			});

		}catch(Exception e){
			CommonDialog.PopupPrompt("获取配置信息异常："+e.getMessage(), null);
		}
		
		requestCurrOrderList();
		requestDinnerList();
		
		refreshUserProp();
	}
		
	private void refreshUserProp(){
		m_username.setText(MainPanel.getCurrUser().getName());
		m_remain.setText("￥" + MainPanel.getCurrUser().getRemainMoney());
		m_total.setText("￥" + MainPanel.getCurrUser().getTotalPay());
	}
	
	private void requestUserProp(){
		
		try{
			MainPage.fsm_server.logonServer(MainPanel.getCurrUser().getName(),MainPanel.getCurrUser().getPass(), new AsyncCallback<String>() {
				
				@Override
				public void onSuccess(String result) {
					
					if(result.startsWith("<Error>")){
						CommonDialog.PopupPrompt(result, null);
						return ;
					}
					try{
						MainPanel.getCurrUser().fromJSON(new YuchJSONObject(result));
						
						refreshUserProp();
						
					}catch(Exception e){
						CommonDialog.PopupPrompt("requestUserProp: " + e.getMessage(), null);
					}
											
				}
				
				@Override
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt(caught.getMessage(), null);
				}
			});
		}catch(Exception e){
			CommonDialog.PopupPrompt(e.getMessage(), null);
		}
	}
	
	
	private void requestCurrOrderList(){
		
		m_currOrderTable.removeAllRows();
		m_formerOrderTable.removeAllRows();
		
		try{
			
			MainPage.fsm_server.getCurrOrderList(MainPanel.getCurrUser().getName(),
			new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("获取用户订单信息失败：" + caught.getMessage(), null);
				}

				public void onSuccess(String result) {
					processCurrOrderList(result);
				}
			});
			
				
			MainPage.fsm_server.getFormerOrderList(MainPanel.getCurrUser().getName(),
			new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("获取用户上次订单信息失败：" + caught.getMessage(), null);
				}

				public void onSuccess(String result) {
					try{
						
						m_formerOrderList.clear();
						
						YuchJSONObject t_json = new YuchJSONObject(result);
						for(int i = 0 ;i < t_json.m_jsonArray.size();i++){
							Order t_order = new Order();
							t_order.fromJSON(new YuchJSONObject((JSONObject)t_json.m_jsonArray.get(i)));
							
							if(!t_order.isCommented()){
								m_formerOrderList.add(t_order);
							}								
						}
						
						refreshFormerOrderList();
						
					}catch(Exception e){
						CommonDialog.PopupPrompt("处理用户上次订单信息失败：" + e.getMessage(), null);
					}
					
				}
			});

		}catch(Exception e){
			CommonDialog.PopupPrompt("获取用户订单信息异常："+e.getMessage(), null);
		}
	}
	
	private static RankPanel[] getDinnerRank(){
		RankPanel[] t_rank	= 
		{
			new RankPanel("./start_empty.gif","start_mark.gif"),
			new RankPanel("./start_empty.gif","start_mark.gif"),
			new RankPanel("./start_empty.gif","start_mark.gif")
		};
		return t_rank;
	}
	
	private static HTML[] getDinnerRankLabel(){
		HTML[] t_rankLable	= 
		{
			new HTML("色"),
			new HTML("香"),
			new HTML("味"),
		};
		
		return t_rankLable;
	}
	
	private static Widget getRankSumPanel(Dinner _dinner,RankPanel[] _rank,HTML[] _rankLabel,boolean _disable){
		
		VerticalPanel t_panel = new VerticalPanel();
		t_panel.setStyleName("star-table");
		
		for(int i = 0;i < 3;i++){
			HorizontalPanel t_rankPanel = new HorizontalPanel();
			t_rankPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
							
			_rank[i].setEnable(!_disable);
			
			t_rankPanel.add(_rankLabel[i]);
			t_rankPanel.add(_rank[i]);
						
			if(_dinner != null){
				
				Dinner.RankNumber t_number = _dinner.getRand(i);
				
				_rank[i].setRank(t_number.integerDigit);
				if(t_number.decimalDigit == 0 && t_number.integerDigit == 0){
					t_rankPanel.add(new HTML("--"));
				}else{
					t_rankPanel.add(new HTML(Float.toString(t_number.asFloat())));
				}
				
			}
			
			t_panel.add(t_rankPanel);
		}
		
		return t_panel;
	}
	
	private class CommentOrderDlg extends DialogBox {
		
		final Order m_order;
		
		final RankPanel[] m_rank = getDinnerRank();
		final HTML[]	m_rankLable = getDinnerRankLabel();
				
		public CommentOrderDlg(Order _order){
			
			super(false,true);
			
			m_order = _order;
			
			final TextArea	t_commnet	= new TextArea();
			t_commnet.setPixelSize(300, 100);
						
			VerticalPanel t_mainPane = new VerticalPanel();
			
			t_mainPane.add(new HTML("写下您的吃后感："));
			t_mainPane.add(t_commnet);
			t_mainPane.add(getRankSumPanel(null,m_rank,m_rankLable,false));
			
			HorizontalPanel t_btnPanel = new HorizontalPanel();
			t_btnPanel.setSpacing(10);
			t_btnPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
			
			Button t_confim = new Button("确认");
			Button t_cancel = new Button("取消");
			
			t_btnPanel.add(t_confim);
			t_btnPanel.add(t_cancel);
			
			t_mainPane.add(t_btnPanel);
			
			setWidget(t_mainPane);
			setText("评价[" + _order.getDinnerName() + "]");
			setAnimationEnabled(true);
			setGlassEnabled(true);
			
			center();			
			
			t_confim.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					try{
						byte[] t_rankValue = new byte[m_rank.length];
						for(int i = 0;i < t_rankValue.length;i++){
							t_rankValue[i] = (byte)m_rank[i].getRank();
							if(t_rankValue[i] == 0){
								CommonDialog.PopupPrompt("请给色香味打分!" , CommentOrderDlg.this);
								return;
							}
						}
						MainPage.fsm_server.commentOrder(MainPanel.getCurrUser().getName(), t_commnet.getText(), t_rankValue, m_order.getTime(),
						new AsyncCallback<String>(){
							
							public void onFailure(Throwable caught) {
								CommonDialog.PopupPrompt("评论失败：" + caught.getMessage(), CommentOrderDlg.this);
							}

							public void onSuccess(String result) {
								if(result.startsWith("<Error>")){
									CommonDialog.PopupPrompt(result, CommentOrderDlg.this);
									return;
								}
								
								m_formerOrderList.remove(m_order);
								refreshFormerOrderList();
								
								CommonDialog.PopupPrompt("评论成功！", CommentOrderDlg.this);
								
								hide();
							}
						});
						
					}catch(Exception e){
						CommonDialog.PopupPrompt("评论异常："+e.getMessage(), CommentOrderDlg.this);
					}			
				}
			});
			
			t_cancel.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					hide();				
				}
			});
		}
		
	}
	
	private void refreshFormerOrderList(){
		
		m_formerOrderTable.removeAllRows();
		
		int t_column = 0;
		
		m_formerOrderTable.setWidget(0, t_column++, new HTML("<b>菜名</b>"));
		m_formerOrderTable.setWidget(0, t_column++, new HTML("<b>菜价</b>"));
		m_formerOrderTable.setWidget(0, t_column++, new HTML("<b>下单时间</b>"));
		m_formerOrderTable.setWidget(0, t_column++, new HTML("<b>下单人</b>"));
		m_formerOrderTable.setWidget(0, t_column++, new HTML("<b>评价操作</b>"));
		
		synchronized (m_formerOrderList) {
			for(int i = 0 ;i < m_formerOrderList.size();i++){
				final Order t_order = m_formerOrderList.get(i);
				
				t_column = 0;
				final Button t_opBtn = new Button("评价");
				
				m_formerOrderTable.setWidget(i + 1,t_column++,new HTML(t_order.getDinnerName()));
				m_formerOrderTable.setWidget(i + 1,t_column++,new HTML(Double.toString(t_order.getPayMoney())));
				
				fsm_dateTime.setTime(t_order.getTime());				
				m_formerOrderTable.setWidget(i + 1,t_column++,new HTML(fsm_orderTimeFormat.format(fsm_dateTime)));
				m_formerOrderTable.setWidget(i + 1,t_column++,new HTML(t_order.getUserName()));
				
				m_formerOrderTable.setWidget(i + 1,t_column++,t_opBtn);
				
				t_opBtn.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						new CommentOrderDlg(t_order).show();					
					}
				});
			}
		}
		
	}
	
	private void requestDinnerList(){
		
		m_currDinnerTable.removeAllRows();
		
		try{
			
			MainPage.fsm_server.getCurrDinnerList(new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					CommonDialog.PopupPrompt("获取菜单信息失败：" + caught.getMessage(), null);
				}

				public void onSuccess(String result) {
					processCurrDinnerList(result);
				}
			});

		}catch(Exception e){
			CommonDialog.PopupPrompt("获取菜单信息异常："+e.getMessage(), null);
		}
	}
	
	
	
	private void processCurrOrderList(String _result){
		
		m_currOrderList.clear();
		
		try{
									
			YuchJSONObject t_json = new YuchJSONObject(_result);
			for(int i = 0 ;i < t_json.m_jsonArray.size();i++){
				Order t_order = new Order();
				t_order.fromJSON(new YuchJSONObject((JSONObject)t_json.m_jsonArray.get(i)));
				
				m_currOrderList.add(t_order);				
			}
			
			refreshCurrOrderList();
			
		}catch(Exception e){
			CommonDialog.PopupPrompt("processCurrOrderList：" + e.getMessage(), null);
		}
		
	}
	
	private void refreshCurrOrderList(){
		
		m_currOrderTable.removeAllRows();
		
		int t_column = 0;
		
		m_currOrderTable.setWidget(0, t_column++, new HTML("<b>菜名</b>"));
		m_currOrderTable.setWidget(0, t_column++, new HTML("<b>菜价</b>"));
		m_currOrderTable.setWidget(0, t_column++, new HTML("<b>下单时间</b>"));
		m_currOrderTable.setWidget(0, t_column++, new HTML("<b>下单人</b>"));
		m_currOrderTable.setWidget(0, t_column++, new HTML("<b>取消操作</b>"));
		
		synchronized (m_currOrderList) {
			
			for(int i = 0 ;i < m_currOrderList.size();i++){
				final Order t_order = m_currOrderList.get(i);
				
				t_column = 0;
				final Button t_del = new Button("取消");
				
				m_currOrderTable.setWidget(i + 1,t_column++,new HTML(t_order.getDinnerName()));
				m_currOrderTable.setWidget(i + 1,t_column++,new HTML(Double.toString(t_order.getPayMoney())));
				
				fsm_dateTime.setTime(t_order.getTime());				
				m_currOrderTable.setWidget(i + 1,t_column++,new HTML(fsm_orderTimeFormat.format(fsm_dateTime)));
				m_currOrderTable.setWidget(i + 1,t_column++,new HTML(t_order.getUserName()));
				
				m_currOrderTable.setWidget(i + 1,t_column++,t_del);
				
				t_del.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						CommonDialog.PopupYesNoDlg("你想要取消 [" + t_order.getDinnerName() + "] 这个订单么?" , 
						new YesNoHandler() {
							
							@Override
							public void Process() {
								
								t_del.setEnabled(false);
								
								try{
									
									MainPage.fsm_server.delOrder(t_order.getUserName(), t_order.getTime(),new AsyncCallback<String>(){
										
										public void onFailure(Throwable caught) {
											CommonDialog.PopupPrompt("删除菜单信息失败：" + caught.getMessage(), null);
											t_del.setEnabled(true);
										}

										public void onSuccess(String result) {
											
											t_del.setEnabled(true);
											
											if(result.startsWith("<Error>")){
												CommonDialog.PopupPrompt(result, null);
												return ;
											}
																					
											if(result.length() == 0){
												// maybe the administrator delete this order
												//
												requestCurrOrderList();
											}else{
												String[] t_timeList = result.split(";");
												
												for(String t:t_timeList){
													if(t.length() != 0){

														long time = Long.valueOf(t).longValue();
														
														synchronized (m_currOrderList) {
															for(Order o:m_currOrderList){
																if(o.getTime() == time){
																	m_currOrderList.remove(o);
																	break;
																}
															}
														}
														
													}
												}
												
												// refresh current own order list
												//
												refreshCurrOrderList();
											}
											
											
											// refresh the user property
											requestUserProp();
											
										}
									});
									
								}catch(Exception e){
									CommonDialog.PopupPrompt("删除菜单信息异常："+e.getMessage(), null);
									t_del.setEnabled(true);
								}
							}
						},null);
						
					}
				});
			}
		}		
	}
	
	private void processCurrDinnerList(String _result){
		
		m_currDinnerTable.removeAllRows();
		
		try{
			int t_column = 0;
			
			m_currDinnerTable.setWidget(0, t_column++, new HTML("<b>菜名</b>"));
			m_currDinnerTable.setWidget(0, t_column++, new HTML("<b>菜价</b>"));
			m_currDinnerTable.setWidget(0, t_column++, new HTML("<b>下单次数</b>"));
			m_currDinnerTable.setWidget(0, t_column++, new HTML("<b>评价</b>"));
			m_currDinnerTable.setWidget(0, t_column++, new HTML("<b>下单</b>"));
									
			YuchJSONObject t_json = new YuchJSONObject(_result);
			
			assert t_json.m_jsonArray != null;
			
			for(int i = 0 ;i < t_json.m_jsonArray.size();i++){
							
				final Dinner t_dinner = new Dinner();
				t_dinner.fromJSON(new YuchJSONObject((JSONObject)t_json.m_jsonArray.get(i)));

				final Button t_add = new Button("下单");
				
				t_column = 0;
				m_currDinnerTable.setWidget(i + 1, t_column++, new HTML(t_dinner.getName()));
				m_currDinnerTable.setWidget(i + 1, t_column++, new HTML("￥" + t_dinner.getPrice()));
				m_currDinnerTable.setWidget(i + 1, t_column++, new HTML(Integer.toString(t_dinner.getOrderNum())));
				m_currDinnerTable.setWidget(i + 1, t_column++, getRankSumPanel(t_dinner,getDinnerRank(),getDinnerRankLabel(),true));
				m_currDinnerTable.setWidget(i + 1, t_column++, t_add);
				
				t_add.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						
						t_add.setEnabled(false);
						
						try{
							
							MainPage.fsm_server.addOrder(MainPanel.getCurrUser().getName(), t_dinner.getName(),new AsyncCallback<String>(){
								
								public void onFailure(Throwable caught) {
									CommonDialog.PopupPrompt("下单信息失败：" + caught.getMessage(), null);
									t_add.setEnabled(true);
								}

								public void onSuccess(String result) {
									t_add.setEnabled(true);
									
									if(result.startsWith("<Error>")){
										CommonDialog.PopupPrompt(result, null);
										return ;
									}
									
									try{
										Order t_order = new Order();
										t_order.fromJSON(new YuchJSONObject(result));
										
										m_currOrderList.add(t_order);
										
										// refresh the user property
										requestUserProp();
										
										// refresh current order
										refreshCurrOrderList();
										
									}catch(Exception e){
										CommonDialog.PopupPrompt("processCurrDinnerList ：" + e.getMessage(), null);
									}
								}
							});
							
						}catch(Exception e){
							CommonDialog.PopupPrompt("下单信息异常：" + e.getMessage(), null);
							t_add.setEnabled(true);
						}
					}
				});
			}
			
			// notifiy the dinnerPanel to refresh data
			//
			DinnerPanel.refreshDinnerList(t_json.m_jsonArray);
					
		}catch(Exception e){
			CommonDialog.PopupPrompt("processCurrDinnerList：" + e.getMessage(), null);
		}
	}
	
	
}

